<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applyId">
            <UserSelect
              v-model="form.applyId"
              :placeholder="this.$t('选择用户')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <DatePicker v-model="form.applyTime" :placeholder="$t('申请时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('费用金额(元)')" prop="amountMoney">
            <money v-model="form.amountMoney" :placeholder="$t('费用金额(元)')" />
          </el-form-item>
        </el-col>
        <el-col
          v-if="form.payCompletionTime !== null && form.payCompletionTime !== '' && form.payCompletionTime !== undefined"
          :span="10"
        >
          <el-form-item :label="$t('付款完成时间')" prop="payCompletionTime">
            <DatePicker v-model="form.payCompletionTime" type="date" disabled format="yyyy-MM-dd" value-format="yyyy-MM-dd" :placeholder="$t('付款完成时间')" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.department !== null && form.department !== undefined && form.department !== ''" :span="2">
          <br><br>
          <div class="el-form-item__content" style="margin-left: 120px;">
            <el-button @click="openProcessInfoForm(form.actId)">{{ $t('查看') }}</el-button>
          </div>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="costsThat">
            <el-input v-model="form.costsThat" type="textarea" :placeholder="$t('备注')" maxlength="2000" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" data-type="deal_expense" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="deal:expense" :menu-key="menuKey" :btn-hide="btnHide" />
    </div>
    <el-dialog :visible.sync="infoOpen" :title="$t('流程详情')" :destroy-on-close="true" custom-class="dialogForm" style=" text-align: left;" append-to-body :close-on-click-modal="false" :lock-scroll="false">
      <ProcessInfoForm ref="processInfoForm" />
    </el-dialog>
    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
  import { saveDealExpense, getDealExpense } from '@/api/deal/expense/expense'
  import { getFdSubjectList } from '@/api/fd/config/getTypeMain'
  import { moneyFormat } from '@/utils/ruoyi'
  import { getDealName } from '@/api/base/deal/dealBase'
  import ProcessInfoForm from '@/views/act/process/processInfoForm'
  export default {
    components: {
      ProcessInfoForm
    },
    data() {
      const checkAmountMoney = (rule, value, callback) => {
        if (!value || value === 0) {
          callback(new Error(this.$t('必填信息')))
        } else {
          callback()
        }
      }
      return {
        // 菜单标识
        menuKey: 'deal_expense',
        infoOpen: false,
        // 是否隐藏其它按钮
        otherBtnHide: false,
        // 是否隐藏保存按钮
        btnHide: false,
        // 表单参数
        form: {
          // 费用明细
          dealExpenseDetailList: [],
          fileList: []
        },
        // 表单校验
        rules: {
          applyId: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
          applyTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
          amountMoney: [{ required: true, validator: checkAmountMoney, trigger: 'blur' }],
          actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
        },
        // 遮罩层
        loading: false,
        // 付款大类
        getFdSubjectList: [],
        // 上传文件
        fileList: []
      }
    },
    computed: {
    },
    created() {
      // 付款大类
      getFdSubjectList('expense').then(response => {
        this.getFdSubjectList = this.changeSubjectList(response.data)
      })
      this.$bus.$emit('async_done')
    },
    mounted() {
    },
    methods: {
      changeSubjectList(val) {
        const arr = []
        if (val.length !== 0) {
          val.forEach(item => {
            const obj = {}
            obj.value = item.value
            obj.label = this.$t(item.label)
          if (item.children && item.children.length > 0) {
              obj.children = this.changeSubjectList(item.children)
            }
            arr.push(obj)
          })
        }
        return arr
      },
      // 初始化数据
      init(data) {
        this.loading = true
        if (data != null && data.id !== undefined) {
          getDealExpense(data.id).then(response => {
            this.form = response.data
            this.loading = false
          })
        } else {
          this.reset()
          this.loading = false
        }
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          dealId: this.$route.query.id,
          applyId: this.$store.state.user.userId,
          applyTime: new Date(),
          department: undefined,
          amountMoney: undefined,
          costsThat: undefined,
          actId: undefined,
          actStatus: undefined,
          fileList: [],
          remark: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined,
          dealExpenseDetailList: undefined,
          getFdSubjectList: []
        }
        try {
          this.resetForm('form')
        } catch (e) {
          console.log(e)
        }
      },
      // 取消按钮
      cancel() {
        this.$parent.$parent.formOpen = false
        this.$parent.$parent.reset()
      },
      // 关闭form页面
      closeForm() {
        // 关闭form页面遮罩层
        this.loading = false
        // 关闭form页面
        if (this.$parent.$parent.formOpen !== undefined) {
          this.$parent.$parent.formOpen = false
        }
        // 刷新list页面
        if (this.$parent.$parent.getList !== undefined) {
          this.$parent.$parent.getList()
        }
      },
      /** 提交按钮 */
      submitForm: function(type) {
        return new Promise((resolve, reject) => {
          this.$refs['form'].validate(valid => {
            // 验证数据
            if (valid) {
              // 弹出遮罩层
              this.loading = true
              // 保存数据
              saveDealExpense(this.form).then(response => {
                if (response.code === 200) {
                  // 点击的按钮是保存并启动流程
                  if (type === 'process') {
                    // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                    this.form.id = response.data.id
                    // 启动流程
                    this.startProcess(response.data)
                    // 点击的仅保存
                  } else {
                    this.msgSuccess(this.$t('保存成功'))
                    // 关闭form页面
                    this.closeForm()
                  }
                  resolve()
                } else {
                  this.msgError(response.msg)
                  this.loading = false
                  reject()
                }
              }).catch(() => {
                this.loading = false
              })
            } else {
              this.locationError(document)
            }
          })
        })
      },
      // 启动流程
      startProcess: async function(data) {
        this.loading = false
        var dealName = await getDealName(this.$route.query.id)
        // 启动流程时候传入的参数
        const processData = {}
        // 待办标题
        processData.title = '「' + dealName + '」' + ':' + this.form.actTitle + '(' + moneyFormat(data.amountMoney) + this.$t('元') + ')'
        // 业务表名
        processData.dataTable = 'deal_expense'
        // 业务ID
        processData.dataId = data.id
        // 业务表单地址(待办页面需要打开的页面)
        processData.formPath = '@/views/deal/expense/dealExpenseForm'
        processData.viewPath = '@/views/deal/expense/dealExpenseView'
        // 菜单标识(根据菜单标识判断的走哪个流程)
        processData.menuKey = this.menuKey
        this.startProcessByMenu(processData, () => {
          this.form.actStatus = 'D'
          this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
          this.closeForm()
        })
      },
      // 预览附件
      onlinePreview(row) {
        this.$refs.OnlinePreview.onlinePreviewFile(row.id)
      },
      // 打开流程详情页面 查看OA 报销
      openProcessInfoForm(actId) {
        if (actId) {
          this.infoOpen = true
          this.$nextTick(() => {
            this.$refs.processInfoForm.init({ actId: actId })
          })
        } else {
          this.msgError(this.$t('流程ID为空,不能查看流程信息'))
        }
      }

    }
  }
</script>
<style lang="scss" scoped>

</style>
